from fastapi import APIRouter, File, UploadFile, Request
from fastapi_pagination import Page

from .storages import FileStorageType

from . import schemas, models, storages
from typing import Optional

router = APIRouter()


@router.post("/upload", response_model=schemas.FileServerOutSchema)
async def upload_file(request: Request, file: UploadFile = File(...)):
    storage = storages.StorageFactory.get_storage(FileStorageType.LOCAL)
    file_info = await storage.generate_file_info(file)
    obj = await models.FileServer.create(**file_info, active=True)
    if not obj.file_url.startswith("http"):
        obj.file_url = f"{request.base_url}{obj.file_url}"
    return obj


@router.get("/list", response_model=Page[schemas.FileServerOutSchema])
async def get_file_list(
    request: Request,
    page: Optional[int] = 1,
    size: Optional[int] = 10,
):
    query = models.FileServer.all()
    total = await query.count()
    pages = total // size + 1
    paginated_query = await query.limit(size).offset((page - 1) * size)
    items = []
    for obj in paginated_query:
        if not obj.file_url.startswith("http"):
            obj.file_url = f"{request.base_url}{obj.file_url}"
        items.append(obj)
    return {
        "total": total,
        "pages": pages,
        "size": size,
        "page": page,
        "items": items,
    }
